import React, {FunctionComponent, Suspense} from 'react'
import {HashRouter, Route, Switch} from 'react-router-dom'
import Loading from "../components/loading";
import Iframe from "../components/iframe";
import {connect} from "react-redux";
import {MainInterface} from "../interface/ApplicationInterface";
import {MenuInterface, RouterConfig} from "../store/interface/MenuInterface";
import Empty from "../components/Empty";

/**
 * 陈夕 2:35 下午
 * desc: 右侧组件加载区域组件
 **/
let RouterInit: boolean = false; // 路由初始化标记
const Main: FunctionComponent<MainInterface> = (props) => {
    const {menu} = props;
    const getRoute = (config: RouterConfig) => {
        switch (config.type) {
            case "router":
                return <Route exact key={config.path} path={config.path}
                              component={config.component ? config.component : Empty}/>
            case "iframe":
                return <Route exact key={config.path} path={config.path} render={() => <Iframe url={config.url}/>}/>
            case "redirect":
                // if (!config.component) message.warn("可能缺少相关页面")
                return <Route exact key={config.path} path={config.path}
                              component={config.component ? config.component : Empty}/>
        }
    }

    const routes = React.useMemo(() => {
        if (!menu) return [];
        RouterInit = true;
        return menu.map(item => getRoute(item));
    }, [menu]);

    return (
        <HashRouter>
            <Suspense fallback={<Loading/>}>
                <Switch>
                    {routes}
                    {
                        RouterInit ?
                            <Route exact render={() => <Empty/>}/> :
                            <Route exact component={Loading}/>
                    }
                </Switch>
            </Suspense>
        </HashRouter>
    )
}
export default connect((state: { menu: MenuInterface }) => ({...state.menu}))(Main);
